//
//  BKViewModel.m
//  baokaodaxue
//
//  Created by dangyangyang on 15/5/24.
//  Copyright (c) 2015年 xxx. All rights reserved.
//

#import "BKArchinveViewModel.h"
#import <AFNetworking.h>

@interface BKArchinveViewModel()
@property (nonatomic ,strong) NSMutableArray *colleageArray;

@end


@implementation BKArchinveViewModel


+ (id)share{
    
    static id sharedInstance;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        
        sharedInstance = [[BKArchinveViewModel alloc] init];
    });
    
    return sharedInstance;
    
}
- (id)init{

    self= [super init];
    if (self) {
        _colleageArray = [NSMutableArray array];
    }
    return self;
}

- (void)provWithSuccess:(void (^)(NSArray *))success
                failure:(void (^)(NSString *))failure{

    
   
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    [manager GET:@"http://www.baokaodaxue.com/bk/index/getprov"
      parameters:nil
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSDictionary *responseDic=[NSJSONSerialization
                                       JSONObjectWithData:responseObject
                                       options:NSJSONReadingMutableLeaves
                                       error:nil];
             if ([[responseDic objectForKey:@"code"] isEqualToString:@"200"]) {
                 NSDictionary *extraData = [responseDic objectForKey:@"extraData"];
                 NSMutableArray *dataArray = [NSMutableArray array];
                 for (id key in extraData) {
                     [dataArray addObject:[extraData objectForKey:key]];
                 }
                 success(dataArray);
             }else{
                 failure([responseDic objectForKey:@"message"]);
                 
             }
             
    }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             failure(@"网络连接失败");
    }];
}


- (void)searchWithParams:(NSDictionary *)params
                 success:(void (^)(NSArray *))success
                 failure:(void (^)(NSString *))failure{
    if ([params[@"page"] isEqual:@"1"]) {
        [_colleageArray removeAllObjects];
    }
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
   
    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    [manager GET:@"http://www.baokaodaxue.com/bk/mobile/search"
      parameters:params
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSDictionary *responseDic=[NSJSONSerialization
                                        JSONObjectWithData:responseObject
                                        options:NSJSONReadingMutableLeaves
                                        error:nil];
             if ([[responseDic objectForKey:@"code"] isEqualToString:@"200"]) {
                 NSDictionary *extraData = [responseDic objectForKey:@"extraData"];
                 NSArray *infoArray = [extraData objectForKey:@"info"];
                 if ([infoArray count]>0) {
                     
                     [_colleageArray addObjectsFromArray:infoArray];
                     success(_colleageArray);
                 }else{
                     if ([params[@"page"] isEqual:@"1"]) {
                         failure(@"没有符合条件的大学");
                     }else{
                     
                         failure(@"已全部加载");
                     }
                     
                 
                 }
                 
             }else{
                 failure([responseDic objectForKey:@"message"]);
                 
             }
             
         }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             failure(@"网络连接失败");
         }];

    
}

- (void)submitWithCid:(NSInteger) row
              success:(void (^)(NSString *colleage))success
              failure:(void (^)(NSString *))failure{
    NSURL *url = [NSURL URLWithString:@"http://www.baokaodaxue.com/bk/mobile/setmeng"];
    
    NSString *post = [NSString stringWithFormat:@"cid=%@",[[_colleageArray objectAtIndex:row] objectForKey:@"cid"]];
    
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:postData];
    [request setTimeoutInterval:10.0];
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    
    
    NSDictionary *cookieDic = [userDefault objectForKey:@"Cookie"];
    NSString *cookieString = [NSString stringWithFormat:@"%@=%@",cookieDic[@"name"],cookieDic[@"value"]];
    
    [request setValue:cookieString forHTTPHeaderField:@"Cookie"];
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    
    __weak BKArchinveViewModel *weakSelf = self;
    
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:queue
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
                               if (error) {
                                   NSLog(@"Httperror:%@%ld", error.localizedDescription,(long)error.code);
                               }else{
                                   NSDictionary *responseDic=[NSJSONSerialization JSONObjectWithData:data
                                                                                             options:NSJSONReadingMutableLeaves
                                                                                               error:nil];
                                   
                                   if ([[responseDic objectForKey:@"code"] isEqualToString:@"200"]) {
                                       success([weakSelf.colleageArray[row] objectForKey:@"name"]);
                                       
                                       
                                   }else{
                                       
                                       NSString *messge = [responseDic objectForKey:@"message"];
                                       if ([messge isEqualToString:@"请先登录"]) {
                                           NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                                           [userDefaults removeObjectForKey:@"Cookie"];
                                        
                                       }
                                       failure([responseDic objectForKey:@"message"]);
                                   }
                               }
                           }];


    
}
@end
